const express = require('express');
const router = express.Router();
const db = require('../db/db'); // 导入数据库
const md5 = require('md5'); // MD5
const jsonwebtoken = require('jsonwebtoken') // jst
const salt = 'skldjflskjdflsjdlfjlsdjflsjdfljsldfjwiodhfiwehdfjksh,vnkshbg'; // 密钥
// 首页轮播图
router.get('/index_swipe', (req, res) => {
    let sql = 'SELECT image,link FROM juanpi_index_swipe';
    db.query(sql, (error, result) => {
        if (error) {
            res.json({
                "code": 404,
                "error": error
            });
            return;
        } else {
            res.json({
                "code": 200,
                "data": result
            })
        }
    })
})
// 首页分类
router.get('/index_class', (req, res) => {
    let sql = 'SELECT * FROM juanpi_index_class';
    db.query(sql, (error, result) => {
        if (error) {
            res.json({
                "code": 404,
                "error": error
            })
        } else {
            res.json({
                "code": 200,
                "data": result
            })
        }
    })
})
// 首页精品专场
router.get('/index_scene', (req, res) => {
    let sql = 'SELECT * FROM juanpi_scene';
    db.query(sql, (error, result) => {
        if (error) {
            res.json({
                "code": 404,
                "error": error
            })
        } else {
            res.json({
                "code": 200,
                "data": result
            })
        }
    })

})
// 首页精选单品
router.get('/index_shop', (req, res) => {
    let sql = 'SELECT * FROM juanpi_shop';
    db.query(sql, (error, result) => {
        if (error) {
            res.json({
                "code": 404,
                "error": error
            })
        } else {
            res.json({
                "code": 200,
                "data": result
            })
        }
    })

})
// 分类
router.get('/big_class', (req, res) => {
    let sql = 'SELECT * FROM juanpi_class_big';
    db.query(sql, (error, result) => {
        if (error) {
            res.json({
                "code": 404,
                "error": error
            })
        } else {
            res.json({
                "code": 200,
                "data": result
            })
        }
    })
})
router.get('/middle_class', (req, res) => {
    let sql = `SELECT * FROM juanpi_class_middle WHERE class_id = ${req.query.id}`;
    db.query(sql, (error, result) => {
        if (error) {
            res.json({
                "code": 404,
                "error": error
            })
        } else {
            res.json({
                "code": 200,
                "data": result
            })
        }
    })
})
// 分类子页面
router.get('/class_children', (req, res) => {
    let sql = `SELECT * FROM juanpi_shop WHERE middle_id = ${req.query.id};`;
    db.query(sql, (error, result) => {
        if (error) {
            res.json({
                "code": 404,
                "error": error
            })
        } else {
            res.json({
                "code": 200,
                "data": result
            })
        }
    })
})
// 分类子页面 正序
router.get('/class_children_asc', (req, res) => {
    let sql = `SELECT * FROM juanpi_shop WHERE middle_id = ${req.query.id} ORDER BY shop_price asc;`;
    db.query(sql, (error, result) => {
        if (error) {
            res.json({
                "code": 404,
                "error": error
            })
        } else {
            res.json({
                "code": 200,
                "data": result
            })
        }
    })
})
// 分类子页面 倒序
router.get('/class_children_desc', (req, res) => {
    let sql = `SELECT * FROM juanpi_shop WHERE middle_id = ${req.query.id} ORDER BY shop_price desc;`;
    db.query(sql, (error, result) => {
        if (error) {
            res.json({
                "code": 404,
                "error": error
            })
        } else {
            res.json({
                "code": 200,
                "data": result
            })
        }
    })
})
// 搜索
router.get('/search', (req, res) => {
    let name = req.query.name;
    let sql = "SELECT * FROM juanpi_shop WHERE shop_name like '%" + name + "%'";
    db.query(sql, (error, result) => {
        if (error) {
            res.json({
                "code": 404,
                "error": error
            })
        } else {
            res.json({
                "code": 200,
                "data": result
            })
        }
    })
})
// 搜索倒序排序
router.get('/search_desc', (req, res) => {
    let name = req.query.name;
    let sql = "SELECT * FROM juanpi_shop WHERE shop_name like '%" + name + "%' ORDER BY shop_price desc";
    db.query(sql, (error, result) => {
        if (error) {
            res.json({
                "code": 404,
                "error": error
            })
        } else {
            res.json({
                "code": 200,
                "data": result
            })
        }
    })
})
// 搜索正序排序
router.get('/search_asc', (req, res) => {
    let name = req.query.name;
    let sql = "SELECT * FROM juanpi_shop WHERE shop_name like '%" + name + "%' ORDER BY shop_price asc";
    db.query(sql, (error, result) => {
        if (error) {
            res.json({
                "code": 404,
                "error": error
            })
        } else {
            res.json({
                "code": 200,
                "data": result
            })
        }
    })
})
//注册
router.post('/regist', (req, res) => {
    let username = req.body.username;
    let password = req.body.password;
    // console.log(username,password)
    let passwordre = /^[0-9a-zA-Z_]{6,30}$/;
    if (!passwordre.test(password)) {
        res.json({
            'code': 404,
            'error': '密码输入格式不正确'
        })
        return false;
    }
    let sql = 'select count(*) c from juanpi_users where username = ?'
    db.query(sql, username, (err, data) => {
        console.log(data)
        if (err) {
            res.json({
                'code': 404,
                'error': err
            })
            return
        } else {
            if (data[0].c > 0) {
                res.json({
                    'code': 404,
                    'error': '用户名已存在'
                })
                return
            } else {
                sql = 'insert into juanpi_users set ?'
                let data = {
                    username,
                    password: md5(password + salt)
                }
                db.query(sql, data, (err, datas) => {
                    // console.log(datas)
                    if (err) {
                        res.json({
                            'code': 404,
                            'error': err
                        })
                        return
                    } else {
                        res.json({
                            'code': 201
                        })
                    }
                })
            }
        }
    })
})
//登录
router.post('/login', (req, res) => {
    // 获取用户名和密码
    let username = req.body.username;
    let password = req.body.password;
    // console.log(username,password)
    // 验证用户名和密码
    // let usernamere = /^[a-zA-Z][a-zA-Z0-9_]{6,15}$/;
    // if (!usernamere.test(username)) {
    //     res.json({
    //         'code': 404,
    //         'error': '用户名输入不正确'
    //     })
    //     return false;
    // }
    let passwordre = /^[0-9a-zA-Z_]{6,30}$/;
    if (!passwordre.test(password)) {
        res.json({
            'code': 404,
            'error': '密码格式不正确'
        })
        return false;
    }
    let sql = 'select id,password from juanpi_users where username = ?'
    db.query(sql, username, (err, data) => {
        // console.log(data)
        if (err) {
            res.json({
                'code': 404,
                'error': err
            })
            return
        } else {
            if (data.length > 0) {
                if (data[0].password === md5(password + salt)) {
                    let jwt = jsonwebtoken.sign({
                        id: data[0].id
                    }, salt, {
                        expiresIn: 60 * 60
                    })
                    res.json({
                        'code': 201,
                        'data': {
                            'token': jwt,
                            'msg': '登录成功'
                        }
                    })
                    return
                } else {
                    res.json({
                        'code': 404,
                        'error': '密码错误!'
                    })
                    return
                }
            } else {
                res.json({
                    'code': 404,
                    'error': '用户名不存在'
                })
            }
        }
    })
})
//订单分类
router.get('/orderclass', (req, res) => {
    // console.log(req.query)
    let sql = 'select class_names from juanpi_order_class'
    db.query(sql, (err, result) => {
        if (err) {
            res.json({
                'code': 404,
                'error': err
            })
        } else {
            res.json({
                'code': 201,
                'data': result
            })
        }
    })
})
// 添加地址
router.post('/address_add', (req, res) => {
    let id = req.body.id
    // console.log(id)
    // console.log(id)
    if (id == null || id == undefined) {
        let name = req.body.name
        let tel = req.body.tel
        let province = req.body.province
        let city = req.body.city
        let county = req.body.county
        let addressDetail = req.body.addressDetail
        let postalCode = req.body.postalCode
        let isDefault = req.body.isDefault
        let areaCode = req.body.areaCode
        let data = {
            name,
            tel,
            province,
            city,
            county,
            addressDetail,
            postalCode,
            isDefault,
            areaCode
        }
        // console.log(data)
        if (isDefault == true) {
            let sql = 'update juanpi_address set isDefault = 0;insert into juanpi_address set ?'
            db.query(sql, data, (err, result) => {
                // console.log(data)
                if (err) {
                    res.json({
                        'code': 404,
                        'error': err
                    })
                } else {
                    res.json({
                        code: 201
                    })
                }
            })
            return
        } else {
            let sql = 'insert into juanpi_address set ?'
            db.query(sql, data, (err, result) => {
                // console.log(data)
                if (err) {
                    res.json({
                        'code': 404,
                        'error': err
                    })
                } else {
                    res.json({
                        code: 201
                    })
                }
            })
            return
        }

    } else {
        if (req.body.meta === 1234) {
            let sql = `update juanpi_address set isDefault = 0;update juanpi_address set isDefault = 1 where id = ${id} `
            db.query(sql, (err, result) => {
                console.log(result)
                if (err) {
                    res.json({
                        'code': 404,
                        'error': err
                    })
                } else {
                    res.json({
                        'code': 201,
                        'msg': '修改成功'
                    })
                }
            })
            return
        }
        let name = req.body.name
        let tel = req.body.tel
        let province = req.body.province
        let city = req.body.city
        let county = req.body.county
        let addressDetail = req.body.addressDetail
        let postalCode = req.body.postalCode
        let isDefault = req.body.isDefault
        let areaCode = req.body.areaCode
        let data = {
            name,
            tel,
            province,
            city,
            county,
            addressDetail,
            postalCode,
            isDefault,
            areaCode
        }
        // console.log(data)
        // if(isDefault===true){
        let sql = `update juanpi_address set isDefault = 0;update juanpi_address set ? where id = ${id} `
        db.query(sql, data, (err, result) => {
            // console.log(data)
            if (err) {
                res.json({
                    'code': 404,
                    'error': err
                })
            } else {
                res.json({
                    'code': 201,
                    'msg': '修改成功'
                })
            }
        })
        // }
    }
})
//回显地址
router.get('/address_edits', (req, res) => {
    // console.log(req.query.id)
    let id = req.query.id
    let sql = 'select * from juanpi_address where id = ?'
    db.query(sql, id, (err, result) => {
        if (err) {
            res.json({
                'code': 404,
                'error': err
            })
        } else {
            res.json({
                'code': 201,
                'data': result
            })
        }
    })
})
// 地址渲染
router.get('/address_index', (req, res) => {
    let sql = 'select * from juanpi_address'
    db.query(sql, (err, result) => {
        if (err) {
            res.json({
                'code': 404,
                'error': err
            })
        } else {
            res.json({
                'code': 201,
                'data': result
            })
        }
    })
})
// 商品详情
router.get('/shop_details', (req, res) => {
    // console.log(req.query.id);
    let id = req.query.id;
    let sql = `SELECT * FROM juanpi_shop WHERE id = ${id}`;
    db.query(sql, (error, result) => {
        if (error) {
            res.json({
                "code": 404,
                "error": error
            })
        } else {
            // 判断三级标题
            let two_title = '';
            if (result[0].shop_specs_two_title == null) {
                two_title = '';
            } else {
                two_title = result[0].shop_specs_two_title;
            }
            // 判断三级标题
            let three_title = '';
            if (result[0].shop_specs_three_title == null) {
                three_title = '';
            } else {
                three_title = result[0].shop_specs_three_title;
            }
            // 判断二级数据
            let two_data = []
            if (result[0].specs_two_val == null) {
                two_data = []
            } else {
                two_data = result[0].specs_two_val.split(',')
            }
            // 判断三级数据
            let three_data = []
            if (result[0].specs_treen_val == null) {
                three_data = []
            } else {
                three_data = result[0].specs_two_val.split(',')
            }
            // 拼接商品规格参数
            let specs = {
                name: result[0].shop_name,
                price: result[0].shop_price,
                diffPrice: result[0].shop_price_difference,
                stock: result[0].shop_stock,
                title: [result[0].shop_specs_title, two_title, three_title],
                image: result[0].specs_image.split(','),
                specs_one: result[0].specs_val.split(','),
                specs_two: two_data,
                specs_three: three_data
            }
            res.json({
                "code": 200,
                "data": result,
                "specs": specs
            })
        }
    })
})
// 购物车
router.get('/cart_shop', (req, res) => {
    console.log(req.query.id)
    let id = req.query.id
    let sql = 'select * from juanpi_shop where id = ?'
    db.query(sql,id, (err, result) => {
        // console.log(result)
        if (err) {
            res.json({
                'code': 404,
                'error': err
            })
        } else {
            res.json({
                'code': 201,
                'data': result
            })
        }
    })
})
// 删除加入购物车的商品
router.delete('/shop_del', (req, res) => {
    // console.log(req.query)
    let id = req.query.id
    let data = []
    data.push(id)
    data.join(',')
    // console.log(data)
    let sql = `delete from juanpi_shop_cart where id in (${data})`
    db.query(sql, (err, result) => {
        // console.log(result)
        if (err) {
            res.json({
                'code': 404,
                'error': err
            })
        } else {
            res.json({
                'code': 201
            })
        }
    })
})
//加入订单
router.get('/order_confirm', (req, res) => {
    // console.log(req.query.id)
    let id = req.query.id
    let data = []
    data.push(id)
    data.join(',')
    // console.log(id)
    let sql = `select * from juanpi_shop where id in (${data})`
    db.query(sql, (err, result) => {
        // console.log(result)
        if (err) {
            res.json({
                'code': 404,
                'error': err
            })
        } else {
            res.json({
                'code': 201,
                'data': result
            })
        }
    })
})






module.exports = router;